package com.idanchuang.component.config.apollo.util;

import com.zoi7.component.core.base.BaseClass;
import org.jasypt.exceptions.EncryptionOperationNotPossibleException;
import org.jasypt.util.text.BasicTextEncryptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author yjy
 * @date 2020/7/1 15:19
 **/
public class ENCUtil extends BaseClass {

    private static final Logger log = LoggerFactory.getLogger(ENCUtil.class);

    /**
     * 默认密钥
     */
    private static String DEFAULT_PASSWORD = "dcdefault";
    /**
     * 环境变量中的密钥
     */
    private static String ENV_PASSWORD;

    static {
        ENV_PASSWORD = System.getenv("jasypt.encryptor.password");
        if (isBlank(ENV_PASSWORD)) {
            log.warn("Could not found [jasypt.encryptor.password] in System env");
        }
    }

    private static String FORMAT = "ENC(%s)";
    private static Pattern PATTERN = Pattern.compile("^ENC\\((.*)\\)");

    private static BasicTextEncryptor encryptor;

    /**
     * 加密字符
     * @param value 字符
     * @return 加密结果
     */
    public static String encode(String value) {
        init(ENV_PASSWORD != null ? ENV_PASSWORD : DEFAULT_PASSWORD);
        String en = encryptor.encrypt(value);
        return String.format(FORMAT, en);
    }

    /**
     * 加密字符
     * @param value 字符
     * @param password 指定密钥
     * @return 加密结果
     */
    public static String encode(String value, String password) {
        init(password);
        String en = encryptor.encrypt(value);
        return String.format(FORMAT, en);
    }

    /**
     * 解密字符
     * @param enValue 加密信息
     * @return 解密值
     */
    public synchronized static String decode(String enValue) {
        Matcher matcher = PATTERN.matcher(enValue);
        if (matcher.find()) {
            String en = matcher.group(1);
            log.info("解密: {}, en: {}", enValue, en);
            try {
                init(ENV_PASSWORD != null ? ENV_PASSWORD : DEFAULT_PASSWORD);
                return encryptor.decrypt(en);
            } catch (EncryptionOperationNotPossibleException e) {
                if (notBlank(ENV_PASSWORD)) {
                    log.info("Decode encValue failed, try default password");
                    init(DEFAULT_PASSWORD);
                    return encryptor.decrypt(en);
                }
            }
        }
        return enValue;
    }

    public synchronized static String decode(String enValue, String password) {
        Matcher matcher = PATTERN.matcher(enValue);
        if (matcher.find()) {
            String en = matcher.group(1);
            log.info("解密: {}, en: {}", enValue, en);
            init(password);
            return encryptor.decrypt(en);
        }
        return enValue;
    }

    /**
     * 生成密文
     * @param value 值
     */
    public static void generate(String value) {
        System.out.println(encode(value));
    }

    /**
     * 初始化
     */
    private static void init(String password) {
        encryptor = new BasicTextEncryptor();
        encryptor.setPassword(password);
    }

//    public static void main(String[] args) {
//        String origin = "原始长度原始长度原始长度原始长度原始长度";
//        String en = encode(origin, "dcdefault");
//        System.out.println("原始长度: " + origin.length() + ", 密文长度: " + en.length());
//    }


}
